package com.xxxx.server.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.sun.org.apache.regexp.internal.RE;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.utils.RespBean;
import com.xxxx.server.utils.UploadFiles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @Description 个人中心
 * @Author shanxin
 * @Since 2021/6/9 21:30
 */
@RestController
@RequestMapping("/admin")
public class AdminInfoController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,
                    null,authentication.getAuthorities()));
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "更新用户密码")
    @PutMapping("/pass")
    public RespBean updateAdminPassword(@RequestBody Map<String, Object> info){
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(oldPass, pass, adminId);
    }

    @ApiOperation(value = "更新用户头像")
    @PostMapping("/userface")
    public RespBean uploadUserFace(MultipartFile multipartFile, Integer id, Authentication authentication){
        RespBean res = UploadFiles.uploading(multipartFile);
        if (res.getCode()==500){
            return RespBean.error("文件上传失败！");
        }
        String url = (String) res.getObj();
        return adminService.uploadUserFace(url, id, authentication);

    }

}
